package com.xyh.controller;

import com.xyh.po.User;
import com.xyh.service.PermissionService;
import com.xyh.service.UserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author:kyle
 * @Date:2020/12/17 - 15:53
 * @Project:spring_demo1
 * @Package:com.xyh.controller
 * @Version:1.0
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param file
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/register")
    public String register(MultipartFile file, User user, HttpServletRequest request) throws IOException {

        System.out.println("user = " + user);

        String realPath = request.getServletContext().getRealPath("images");

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String newFileName = realPath + "/" + uuid +suffix;

        user.getUserDetail().setUserImg(newFileName);
        boolean flag = userService.insertUser(user);
        if(flag){
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(newFileName));
        }else {
            return "error";
        }

        return "redirect:/success.jsp";
    }

    @RequestMapping("/login")
    public String Login(String username, String password, HttpSession session){

        User user = userService.login(username, password);
        if(user != null){
            session.setAttribute("user",user);
            return "main";
        }
        else{
            return "error";
        }
    }
}
